 package com.facebook.app.shared.facebookData;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import javax.jdo.annotations.Element;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.NotPersistent;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;

import com.facebook.app.shared.clustering.Clusterable;

@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class FacebookFriend extends FacebookData implements Clusterable {

	private static final long serialVersionUID = -4487579706909693872L;
	
	@NotPersistent
	private double[] characteristicClusterVector = new double[0]; // to avoid null values
	
	@Persistent
	@Element(dependent = "true")
	private transient Set<FacebookLike> likes = new HashSet<FacebookLike>(); // to avoid null values

	public FacebookFriend(String name, long id) {
		super(name, id);
	}

	// The default constructor is required for converting JSON Strings to FacebookFriend objects.
	@SuppressWarnings("unused")
	private FacebookFriend() {}

	public Set<FacebookLike> getLikes() {
		return likes;
	}
	
	public void setLikesWithArray(FacebookLike[] likeArray) {
		
		if (likeArray != null) {
			likes = new HashSet<FacebookLike>(Arrays.asList(likeArray));
		} else {
			likes.clear();
		}
	}
	
	/**
	 * Compares the FacebookLikes of this FacebookFriend with all likes in the collection. 
	 */
	public void adaptCharacteristicClusterVectorToLikeCollection(Collection<FacebookLike> likeCollection) {
		
		characteristicClusterVector = new double[likeCollection.size()];

		int i = 0;
		
		for (FacebookLike likeInCollection: likeCollection) {
			if (likes.contains(likeInCollection)) {
				characteristicClusterVector[i] = 1;
			}
			i++;
		}
	}
	
	@Override
	public double[] getCharacteristicClusterVector() {
		return characteristicClusterVector;
	}
	
	@Override
	public String toString() {
		return "FacebookFriend [name=" + getName() + ", id=" + getId() + "]";
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + (int) (getId() ^ (getId() >>> 32));
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		FacebookFriend other = (FacebookFriend) obj;
		if (getId() != other.getId())
			return false;
		return true;
	}

}
